package com.situ.vivamarket.common;


import com.situ.vivamarket.util.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 统一异常处理,一个异常后通知，使用Spring AOP
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    //监听异常，参数是MethodArgumentNotValidException异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<JsonResult> handle(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        ObjectError objectError = allErrors.stream().findFirst().get();
        JsonResult result = JsonResult.fail(objectError.getDefaultMessage());
        return ResponseEntity.badRequest().body(result);
    }
}